// mircoApp/lunarCalendar/lunarGoodDay/lunarGoodDay.js
const { Solar, Lunar } = require("../lunar.js");

Page({

  /**
   * 页面的初始数据
   */
  data: {
    showCalendar: false,
    showBirth: false,
    birthDay: "",
    checkDay: null,
    switchChecked: false,
    keyword: "",
    wordPop: false,
    daylist: [],
    currentDate: new Date().getTime(),
    minDate: new Date(1924, 0, 1).getTime(),

    YI_JI: [
      {
        category: "热门",
        items: ["嫁娶", "订婚", "安床", "动土", "祈福", "求医", "入宅", "开市"]
      },
      {
        category: "婚嫁",
        items: ["嫁娶", "订婚", "纳采", "问名", "纳婿", "归宁", "安床", "合帐", "冠笄", "订盟", "进人口", "裁衣", "挽面", "开容"]
      },
      {
        category: "祭祀",
        items: ["祭祀", "祈福", "求嗣", "开光", "酬神", "造庙", "祀灶", "焚香", "谢土", "出火"]
      },
      {
        category: "丧葬",
        items: ["修坟", "启钻", "破土", "安葬", "立碑", "成服", "除服", "开生坟", "合寿木", "入殓", "移柩", "普渡", "入宅", "安香", "安门"]
      },
      {
        category: "修造",
        items: [
          "修造",
          "起基",
          "动土",
          "上梁",
          "竖柱",
          "开井开池",
          "作陂放水",
          "拆卸",
          "破屋",
          "坏垣",
          "补垣",
          "伐木做梁",
          "作灶",
          "解除",
          "开柱眼",
          "穿屏扇架",
          "盖屋合脊",
          "开厕",
          "造仓",
          "塞穴",
          "平治道涂",
          "作厕",
          "开池",
          "伐木",
          "掘井",
          "扫舍",
          "放水",
          "造屋",
          "合脊",
          "造畜稠",
          "修门",
          "定磉",
          "作梁",
          "修饰垣墙",
          "架马"
        ]
      },
      {
        category: "经商",
        items: ["开市", "挂匾", "纳财", "求财", "开仓", "经络", "酝酿", "作染", "鼓铸", "割蜜"]
      },
      {
        category: "农耕",
        items: ["栽种", "取渔", "结网", "牧养", "安碓磑"]
      },
      {
        category: "学习",
        items: ["习艺", "入学"]
      },
      {
        category: "生活",
        items: ["探病", "见贵", "乘船", "渡水", "出行", "移徙", "分居", "纳畜", "捕捉", "畋猎", "教牛马", "会亲友", "赴任", "求医"]
      },
      {
        category: "忌讳",
        items: ["起基动土", "破屋坏垣", "盖屋", "造仓库", "立券交易", "交易", "立券", "安机", "会友", "求医疗病", "诸事不宜", "馀事勿取", "行丧", "断蚁", "归岫"]
      }
    ]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  formatDate(date) {
    return `${date.getYear()+1900}/${date.getMonth() + 1}/${date.getDate()}`;
  },
  onDayConfirm(date) {
    const [start, end] = date.detail;
    let obj = {};
    obj.diffTimeNum = this.diffTime(start, end);
    obj.showCalendar = false;
    obj.startTime = this.formatDate(start);
    obj.endTime = this.formatDate(end);
    obj.checkDay = `${obj.startTime} - ${obj.endTime}`;
    this.setData(obj);
  },
  onBirthConfirm(e) {
    let obj = {};
    obj.birthDay = this.timestampToTime(e.detail);
    obj.birthDayValue = e.detail;
    obj.showBirth = false;
    this.setData(obj);
  },
  //日期转化
  timestampToTime(timestamp) {
    var date = new Date(timestamp);
    let Y = date.getFullYear() + "/";
    let M =
      (date.getMonth() + 1 < 10 ?
        "0" + (date.getMonth() + 1) :
        date.getMonth() + 1) + "/";
    let D = this.change(date.getDate()) + " ";
    return Y + M + D;
  },
  change(t) {
    if (t < 10) {
      return "0" + t;
    } else {
      return t;
    }
  },
  selectWord(e){
    let {val} = e.currentTarget.dataset;
    this.setData({
      keyword: val,
      wordPop: false
    });
  },
  diffTime(start, end) {
    // 计算两个日期的相差天数
    const date1 = new Date(start);
    const date2 = new Date(end);
    const diffTime = Math.abs(date2 - date1);
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
    // console.log("两个日期的相差天数:::",date1,date2,diffDays);
    return diffDays;
  },
  onSubmit(){
    if(!this.data.startTime) {
      return wx.showToast({
        title: '请选择查询日期',
        icon: 'error',
        duration: 3000,
      });
    }
    if(!this.data.endTime) {
      return wx.showToast({
        title: '请选择查询日期',
        icon: 'error',
        duration: 3000,
      });
    }
    if(!this.data.birthDayValue) {
      return wx.showToast({
        title: '请选择出生日期',
        icon: 'error',
        duration: 3000,
      });
    }
    if(!this.data.keyword) {
      return wx.showToast({
        title: '请选择关键词',
        icon: 'error',
        duration: 3000,
      });
    }
    this.setData({
      daylist: []
    });
    wx.showLoading({
      title: '查询中',
    })

    let date = new Date(this.data.startTime);
    let list = [];
    let memberSX = Lunar.fromDate(new Date(this.data.birthDayValue)).getYearShengXiao();
    console.log('他的生肖：：：',memberSX);

    for (let i=0, j= Number(this.data.diffTimeNum); i<j; i++){
      let gettime = date.getTime() + i*24 * 60 * 60 * 1000;
      let d = Lunar.fromDate(new Date(gettime));
      let solar = Solar.fromDate(new Date(gettime));
      let Yi = d.getDayYi();
      if(Yi.includes(this.data.keyword)) {
        let _Lunar = solar.getLunar().toFullString().split(" ");// 将阴历当天的详情转字符并分割数组
        let _theDaySX = _Lunar[_Lunar.length - 2];//当天冲什么生肖
        let _isXianChong = _theDaySX.includes(memberSX);//判断是否和门主相冲
        let _info = {
          Lunar: _Lunar,
          datetime: solar.getYear() + '/' + solar.getMonth() + '/' + solar.getDay(),
          yearAndMonth: solar.getYear() + '.' + solar.getMonth(),
          day: solar.getDay(),
          diffTime: this.diffTime(date.getTime(),gettime),
          isXianChong: _isXianChong
        };
        list.push(_info);
      }
    }
    this.setData({
      daylist: list
    });
    if(list.length == 0) {
      wx.hideLoading();
      wx.showModal({
        title: '提示',
        content: `该日期范围内暂无 【${this.data.keyword}】 的吉日，可试试选择其他日期`,
        success (res) {
          if (res.confirm) {
            console.log('用户点击确定')
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })

    } else {
      setTimeout(() => {
        wx.hideLoading()
      }, 2000);
    }
  },
  onClickVal(e){
    let {name,val} = e.currentTarget.dataset;
    this.setData({
      [name]: val
    });
  },
  toAlmanac(e) {
    let {time} = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/mircoApp/lunarCalendar/almanac/almanac?data=${time}`
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})